package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private UserService userService;

    @PostMapping
    /**
     * 加入缓存 k--v
     * k = value::key  user::xxxx
     * v = 返回值
     */
    //方法一（常用）
     @CachePut(value = "user",key = "#user.id")
    //方法二
    //@CachePut(value = "user",key = "#root.args[0].id")//#root.args[0]方法参数
    //方法三
    //@CachePut(value = "user",key = "#result.id")//返回值中的id属性
    public User save(User user){
        userService.save(user);
        return user;
    }

    @DeleteMapping("/{id}")
    /**
     * 从缓存中删除数据
     */
    @CacheEvict(value = "user",key = "#id")
    public void delete(@PathVariable Long id){
        userService.removeById(id);
    }

    @PutMapping
    public User update(User user){
        userService.updateById(user);
        return user;
    }

    /**
     * 一：在方法执行前spring先查看缓存中是否有数据，如果有数据，则直接返回缓存数据
     *    若没有数据，调用方法并将方法返回值放到缓存中
     * 二：condition:条件满足，#result 不能使用（未来有版本能用）
     * 三：unless：条件不满足，就加入缓存 ok
     */
    //一
    //@Cacheable(value = "user",key = "#id")
    //二
    //@Cacheable(value = "user",key = "#id",condition = "result !=null ")
    //三
    @Cacheable(value = "user",key = "#id",unless = "#result == null ")
    @GetMapping("/{id}")
    public User getById(@PathVariable Long id){
        User user = userService.getById(id);
        return user;
    }

    @GetMapping("/list")
    @Cacheable(value = "user",key = "#user.id+'_'+#user.name")
    public List<User> list(User user){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(user.getId() != null,User::getId,user.getId());
        queryWrapper.eq(user.getName() != null,User::getName,user.getName());
        List<User> list = userService.list(queryWrapper);
        return list;
    }
}
